import os
import sys
import pygame
from config import Config

def get_font_path():
    """
    获取适合当前操作系统的中文字体路径
    """
    system = sys.platform
    font_path = None
    
    if system == 'win32':
        # Windows系统字体路径
        font_paths = [
            "C:/Windows/Fonts/msyh.ttc",  # 微软雅黑
            "C:/Windows/Fonts/simhei.ttf",  # 黑体
            "C:/Windows/Fonts/simsun.ttc",  # 宋体
        ]
        for path in font_paths:
            if os.path.exists(path):
                font_path = path
                break
    elif system == 'darwin':
        # macOS系统字体路径
        font_paths = [
            "/System/Library/Fonts/PingFang.ttc",  # 苹方
            "/System/Library/Fonts/STHeiti Light.ttc",  # 黑体
            "/Library/Fonts/Arial Unicode.ttf"  # Arial Unicode
        ]
        for path in font_paths:
            if os.path.exists(path):
                font_path = path
                break
    else:
        # Linux系统字体路径
        font_paths = [
            "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",  # 文泉驿微米黑
            "/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf"  # Droid Sans
        ]
        for path in font_paths:
            if os.path.exists(path):
                font_path = path
                break
    
    # 如果找不到系统字体，尝试使用pygame默认字体
    if font_path is None:
        try:
            font_path = pygame.font.get_default_font()
        except:
            pass
    
    return font_path

class FontManager:
    """
    字体管理器，用于缓存和获取不同大小的字体
    """
    _instance = None
    _fonts = {}
    _font_path = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(FontManager, cls).__new__(cls)
            cls._instance._font_path = get_font_path()
        return cls._instance
    
    def get_font(self, size):
        """
        获取指定大小的字体
        """
        if size not in self._fonts:
            try:
                if self._font_path:
                    self._fonts[size] = pygame.font.Font(self._font_path, size)
                else:
                    # 如果找不到合适的字体，使用系统默认字体
                    self._fonts[size] = pygame.font.SysFont(None, size)
            except Exception as e:
                print(f"加载字体失败: {e}")
                # 使用系统默认字体作为后备
                self._fonts[size] = pygame.font.SysFont(None, size)
        
        return self._fonts[size]

def render_text(text, size=Config.FONT_SIZE, color=Config.TEXT_COLOR, bold=False):
    """
    渲染文本，返回文本表面
    
    参数:
        text: 要渲染的文本
        size: 字体大小
        color: 文本颜色
        bold: 是否加粗
    
    返回:
        渲染后的文本表面
    """
    font_manager = FontManager()
    font = font_manager.get_font(size)
    font.set_bold(bold)
    return font.render(text, True, color)

def draw_text(surface, text, position, size=Config.FONT_SIZE, color=Config.TEXT_COLOR, 
              center=False, bold=False):
    """
    在指定位置绘制文本
    
    参数:
        surface: 要绘制到的表面
        text: 要绘制的文本
        position: 文本位置 (x, y)
        size: 字体大小
        color: 文本颜色
        center: 是否居中显示
        bold: 是否加粗
    """
    text_surface = render_text(text, size, color, bold)
    text_rect = text_surface.get_rect()
    
    if center:
        text_rect.center = position
    else:
        text_rect.topleft = position
    
    surface.blit(text_surface, text_rect)
    return text_rect